<template>
    <el-form 
        label-position="left" 
        label-width="100px"
        :model="formData" 
        :rules="rules" 
        ref="ruleForm"
        
    >
        <el-row :gutter="24">
            <el-col :span="24">
                <el-form-item label="所属区域：" prop="areaCode">
                    <el-tree-select
                        v-if="areaFlag"
                        class="customSelectTree"
                        v-model="formData.areaId"
                        :treeParams="areaOptions"
                        :select-params="{
                            // size: 'small',
                            clearable: true,
                            multiple: false,
                            collapseTags: true,
                        }"
                    />
                </el-form-item>
            </el-col>
            <el-col :span="24">
                <el-form-item label="能源类型：" prop="energyCode">
                    <el-select
                        v-model="formData.energyCode"
                        filterable
                        placeholder="请选择"
                        transfer
                        style="width: 100%"
                    >
                        <el-option
                            v-for="item in energyList"
                            :key="item.code"
                            :value="item.code"
                            :label="item.name"
                        />
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="24">
                <el-form-item label="启用年份：" prop="year">
                    <el-date-picker
                        v-model="formData.year"
                        type="year"
                        :editable="false"
                        :clearable="false"
                        style="width: 100%;"
                        class="calendar-single"
                        :pickerOptions="pickerOptions"
                    />
                </el-form-item>
            </el-col>
            <el-col :span="24">
                <el-form-item label="因子值：" prop="carbon">
                    <el-input placeholder="请输入" v-model="formData.carbon" />
                </el-form-item>
            </el-col>
        </el-row>
    </el-form>
</template>
<style lang="scss" scoped>
.customSelectTree ::v-deep.el-select.el-tree-select-input.el-popover__reference {
    width: 100% !important;
}
.calendar-single ::v-deep.el-icon-date:before {
    content: '' !important;
}
.calendar-single ::v-deep.el-input__suffix {
    width: 25px !important;
}
.calendar-single ::v-deep i:last-child {
    background: url('~@/assets/image/operation/calendar.svg') center center no-repeat !important;
    background-size: 18px 18px !important;
}
.calendar-single ::v-deep.el-range-separator {
    line-height: 28px !important;
}
</style>
<script>
    import dayjs from "dayjs";
    import { 
        addAreaCarbonInfo,
        updateAreaCarbonInfo,
    } from "@/api/factorManage";
    import { getAreaTree } from '@/api/regionMessage'
    import { findEnumOptions } from '@/api/common'
    export default {
        name: "FormModal",
        props: {
            title: String,
            rowData: Object
        },
        data() {
            return {
                pickerOptions: {
                    disabledDate(time) {
                        return time.getTime() > new Date().getTime()    //使用这种方法实现
                    },
                },
                areaFlag: false,
                areaOptions: {
                    data: [],
                    clickParent: true, // 父级可以点击
                    props: {
                        'node-key': 'id',
                        children: 'children',
                        label: 'name',
                        value: 'id',
                    },
                    // checkStrictly: true  // 父子节点分离勾选
                },
                energyList:[],
                formData:{
                    projectId:this.$store.state.projectId,
                    areaId:this.$props.rowData?.areaId || null,                
                    energyCode:this.$props.rowData?.energyCode || null,
                    year:this.$props.rowData?.year || dayjs().format('YYYY'),
                    carbon:this.$props.rowData?.carbon || 0,
                },
                rules:{
                    areaId: [
                        { required: true, message: "请选择地区", trigger: "change" }
                    ],
                    energyCode: [
                        { required: true, message: "请选择能源类型", trigger: "change" }
                    ],
                    year: [
                        { required: true, message: "请选择启用年份", trigger: "change" }
                    ],
                    carbon: [
                        { required: true, message: "请输入碳排因子", trigger: "blur" }
                    ],
                }
            }
        },
        created(){
            this.initSetModal()
            this.initArea()
            this.initEnergyList()
        },
        methods:{
            initEnergyList() {
                findEnumOptions('energyType').then(res => {
                    if (res.code === 200) {
                        this.energyList = res.data || [];
                    }
                })
            },
            initArea() {
                getAreaTree().then(res => {
                    if (res.code === 200) {
                        this.areaOptions.data = res.data;
                        this.areaFlag = true;
                    }
                })
            },
            initSetModal() {
                if (this.$props.rowData) {
                    this.$emit("SetTitle", "编辑");
                } else {
                    this.$emit("SetTitle", "新增");
                }
                this.$emit("SetPageWidth", 600);
                this.$emit("SetPageActions", [
                    {
                        text: "取消",
                        theme: "info",
                        handle: () => {
                            this.$emit("Close");
                        }
                    },
                    {
                        text: "保存",
                        theme: "primary",
                        handle: () => {
                            this.submitForm();
                        },
                        loading: false
                    }
                ]);
            },
            submitForm() {
                this.$refs.ruleForm.validate(valid => {
                    if (valid) {
                    //验证成功,发送请求
                    if (this.$props.rowData) {
                        //编辑更新
                        this.sendUpdateRequestFun();
                    } else {
                        //新增
                        this.sendAddRequestFun();
                    }
                    } else {
                    //验证失败
                    }
                });
            },
            sendAddRequestFun() {
                    addAreaCarbonInfo({
                    ...this.formData,
                    year: dayjs(this.formData.year).format('YYYY')
                }).then(result => {
                    if (result.code == 200) {
                        this.$message.success(result.msg);
                        this.$emit("Close", true);
                    }
                }).catch((err) => {
                    this.$message.error(err)
                })
            },
            sendUpdateRequestFun() {
                const params={
                    ...this.formData,
                    id: this.$props.rowData?.id,
                    year: dayjs(this.formData.year).format('YYYY')
                }
                    updateAreaCarbonInfo(params).then(result => {
                    if (result.code == 200) {
                        this.$message.success(result.msg);
                        this.$emit("Close", true);
                    }
                }).catch((err) => {
                    this.$message.error(err)
                })
            },
        }
    }
</script>
